<template>
  <div class="container">
    <el-row class="header">
      <el-col class="asd" :span="14" align="left">
        <el-input
          clearable
          v-model="data.params.projectName"
          placeholder="项目名称/编号/合同名称/合同编号"
          style="width: 300px; margin-right: 15px"
        />
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="10" align="right">
        <el-button v-limit="'XMZX:HTGL:HTGL:EXPORT'" class="ordinary" @click="handleExport()"
          >批量导出</el-button
        >
        <el-button v-limit="'XMZX:HTGL:HTGL:UNLOCK'" type="primary" @click="handleUnlock()"
          >解锁</el-button
        >
        <el-button v-limit="'XMZX:HTGL:HTGL:LOCK'" type="primary" @click="handleLock()"
          >锁定</el-button
        >
        <el-button v-limit="'XMZX:HTGL:HTGL:ADD'" type="primary" @click="handleAdd()"
          >合同新增</el-button
        >
      </el-col>
    </el-row>

    <Table
      :loading="data.isLoading"
      :tableArr="data.allTableData"
      :columns="data.columns"
      :page-size="data.params.size"
      :page-num="data.params.current"
      @selectList="getCurrentList"
      @row-click="handleRowClick"
    >
      <template #status>
        <el-table-column label="状态" width="80">
          <template #default="scope" class="status">
            <span class="stoped-status" v-if="scope.row.lockStatus == 1">已锁定</span>
            <span class="opened-status" v-if="scope.row.lockStatus == 0">正常</span>
          </template>
        </el-table-column>
      </template>
      <template #operate="{ row }">
        <el-button
          v-limit="'XMZX:HTGL:HTGL:EDIT'"
          :disabled="row.lockStatus == 1"
          size="small"
          class="ordinary"
          @click="handleEdit(row)"
          >编辑</el-button
        >
        <el-button
          v-limit="'XMZX:HTGL:HTGL:DETAIL'"
          size="small"
          class="ordinary"
          @click="handleDetail(row)"
          >详情</el-button
        >
      </template>
    </Table>
    <div class="example-pagination-block">
      <el-pagination
        background
        layout="prev, pager, next ,total,sizes,jumper"
        :total="data.total"
        :page-size="data.params.size"
        v-model:current-page="data.params.current"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <el-dialog
      v-model="data.editDialog"
      width="72%"
      top="10vh"
      @close="handleClose"
      :title="data.currentHandle"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="基本信息" name="1">
          <Information
            :title="data.currentHandle"
            ref="baseForm"
            v-if="data.editDialog"
          ></Information>
        </el-tab-pane>
        <el-tab-pane label="项目经费预算" name="2">
          <budegetTable v-if="data.editDialog" :title="data.currentHandle"></budegetTable>
        </el-tab-pane>
        <el-tab-pane label="进度执行" name="3">
          <Schedule v-if="data.editDialog" :title="data.currentHandle"></Schedule>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.editDialog = false">关闭</el-button>
          <el-button v-if="data.currentHandle !== '合同详情'" type="primary" @click="handleSave()"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 导出字段选择 -->
    <Export
      :detailList="data.detailList"
      :showing="data.exportDialog"
      @close="closeExport"
      @handle-filed="handleFiled"
    ></Export>
  </div>
</template>

<script lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'
import tableData from './tableHeader.json'
import Information from './components/information.vue'
import budegetTable from './components/budgetTable.vue'
import Schedule from './components/schedule.vue'
import Table from '../../components/table2/table.vue'
import {
  closeContractStatus,
  exportContractList,
  getContractList,
  insertContract,
  openContractStatus,
  updateContract,
} from '../../api/contract'
import Export from '@/views/project/components/Export/index.vue'
import { useStore } from 'vuex'
import { servicesLoading } from '@/utils/loading'

export default {
  components: {
    Table,
    Information,
    budegetTable,
    Schedule,
    Export,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    const baseForm = ref()
    let data = reactive({
      currentHandle: '合同新增',
      params: {
        projectName: '',
        current: 1,
        size: 10,
      },
      total: 0,
      currentList: [],
      isLoading: false,
      allTableData: [],
      columns: tableData.platformTableHeader,
      ids: [],
      editDialog: false,
      currentRow: {},
      exportDialog: false,
      detailList: [] as any,
    })
    const onSearch = async () => {
      data.isLoading = true
      getContractList(data.params).then((res) => {
        data.isLoading = false
        let records = res.data.data.records
        records.map((item) => {
          if (item.contractStatus == 1) {
            item.contractStatus = '履行中'
          } else if (item.contractStatus == 2) {
            item.contractStatus = '履行异常'
          } else if (item.contractStatus == 3) {
            item.contractStatus = '履行完毕'
          } else if (item.contractStatus == 4) {
            item.contractStatus = '终止'
          }
          // item.signingDate = item.signingDate?.slice(0, 10)
          item.periodDate =
            item.scheduledStartDate && item.scheduledCompletionDate
              ? item.scheduledStartDate?.slice(0, 7) +
                '至' +
                item.scheduledCompletionDate?.slice(0, 7)
              : '暂无'
        })
        data.allTableData = records
        data.total = res.data.data.total
      })
    }
    onSearch()
    const search = () => {
      data.params.current = 1
      onSearch()
    }

    const handleCurrentChange = (e) => {
      data.params.current = e
      onSearch()
    }
    //改变页数限制
    const handleSizeChange = (e) => {
      data.params.size = e
      onSearch()
    }
    const getCurrentList = (currentList) => {
      data.currentList = currentList
      data.ids = currentList.map((item) => {
        return item.id
      })
    }
    let contractForm = reactive(store.state.projectCenter.contractForm)
    const handleEdit = (row) => {
      data.currentHandle = '编辑合同'
      data.editDialog = true
      console.log(row, 'handleEdit')
      for (let key in contractForm) {
        contractForm[key] = JSON.parse(JSON.stringify(row[key])) 
      }
      contractForm.contractPlanList.forEach(item => {
        item.isConfirm = true
      });
      console.log(contractForm.contractBudgetList,'contractForm.contractBudgetList');
    }
    const handleRowClick = (row) => {
      handleDetail(row)
    }
    const handleDetail = (row) => {
      const loading = servicesLoading({ fullscreen: false })
      data.editDialog = true
      data.currentHandle = '合同详情'
      for (let key in contractForm) {
        contractForm[key] = row[key]
      }
      loading.close()
    }
    const handleDel = () => {
      if (data.ids.length) {
        ElMessageBox.alert('您确认删除所选中合同数据吗？', '提示', {
          confirmButtonText: '确认',
          callback: (action) => {
            console.log(action)
          },
        })
      }
    }
    const closeExport = () => {
      data.exportDialog = false
    }
    const handleFiled = (arr) => {
      console.log(arr, 'handleFiled')
      if (arr.length > 0) {
        ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          exportContractList({ ...data.params, ids: data.ids, headList: arr })
          console.log('批量导出')
          data.exportDialog = false
        })
      }
    }
    const handleExport = () => {
      data.exportDialog = true
      data.detailList = [
        { fieldName: 'projectName', title: '项目名称' },
        { fieldName: 'contractName', title: '合同名称' },
        { fieldName: 'projectMainDataCode', title: '项目主数据编码' },
        { fieldName: 'contractNumber', title: '合同编号' },
        { fieldName: 'contractMainDataCode', title: '合同主数据编码' },
        { fieldName: 'contractType', title: '合同类型' },
        { fieldName: 'contractNatureName', title: '合同性质' },
        { fieldName: 'applyingUnitName', title: '申请单位' }, //单位id
        { fieldName: 'partyA', title: '甲方' },
        { fieldName: 'partyB', title: '乙方' },
        { fieldName: 'contractSigningMethodName', title: '合同签订方式' },
        { fieldName: 'contractLanguageName', title: '合同语言' },
        { fieldName: 'involvesMultipleParties', title: '是否涉及多方' },
        { fieldName: 'provisionalSum', title: '暂定金(万元)' },
        { fieldName: 'contractAmount', title: '合同金额(万元)' },
        { fieldName: 'taxRate', title: '税率(%)' },
        { fieldName: 'taxAmount', title: '税额' },
        { fieldName: 'contractNetAmount', title: '合同净额(万元)' },
        { fieldName: 'projectUndertakingUnitName', title: '项目承担单位' },
        { fieldName: 'businessSectorName', title: '业务版块' },
        { fieldName: 'signingDate', title: '签订日期' },
        { fieldName: 'stampingDate', title: '盖章日期' },
        { fieldName: 'scheduledStartDate', title: '规定开工日期' },
        { fieldName: 'performanceCountry', title: '合同履行地(国家)' },
        { fieldName: 'performanceProvince', title: '合同履行地(省)' },
        { fieldName: 'performanceCity', title: '合同履行地(市)' },
        { fieldName: 'projectStartProvinceName', title: '项目起点省' },
        { fieldName: 'projectStartCityName', title: '项目起点市' },
        { fieldName: 'projectEndProvinceName', title: '项目终点省' },
        { fieldName: 'projectEndCityName', title: '项目终点市' },
        { fieldName: 'mileage', title: '里程(KM)' },
        { fieldName: 'businessTypeNme', title: '业务类型' },
        { fieldName: 'businessSubtypeName', title: '业务类型细分' },
        { fieldName: 'engineeringTypeName', title: '工程类型' },
        { fieldName: 'engineeringPhaseName', title: '工程阶段' },
        { fieldName: 'projectLeaderName', title: '项目负责人' },
        { fieldName: 'contractBusinessTypeName', title: '合同业务类型' },
        { fieldName: 'contractBusinessSubtypeName', title: '合同业务类型细分' },
        { fieldName: 'inpayTypeName', title: '收支类型' },
        { fieldName: 'disputeResolutionMethodName', title: '争议解决方式' },
        { fieldName: 'contractTemplateUsageName', title: '合同范本使用情况' },
        { fieldName: 'contractHandlerName', title: '合同承办人' },
        { fieldName: 'contractHandlerContact', title: '合同承办人联系方式' },
        { fieldName: 'managementDepartmentName', title: '管理部门' },
        { fieldName: 'actualPerformanceSubject', title: '合同实际履约主体' },
        { fieldName: 'ourContractingPartyName', title: '我方签约单位' },
        { fieldName: 'contractStatus', title: '合同状态' },
        { fieldName: 'totalAmountCurrency', title: '总金额币种' },
        { fieldName: 'outputReportingMethod', title: '产值填报方式' },
        { fieldName: 'incomeTypeName', title: '收入类型' },
        { fieldName: 'submittedToLegalPersonApproval', title: '是否提交企业法人签批' },
        { fieldName: 'legalPersonSealPermission', title: '是否准许使用法人章' },
        { fieldName: 'numberOfContractCopiesName', title: '持有合同份数' },
        { fieldName: 'storageMethodName', title: '入库方式' },
        { fieldName: 'importantProject', title: '是否为重要项目' },
        { fieldName: 'contractClassificationName', title: '合同分类' },
        { fieldName: 'departmentLeaderApproval', title: '部门领导会签' },
        { fieldName: 'companyLeaderApproval', title: '公司领导会签' },
        { fieldName: 'requiresRelatedManagerApproval', title: '是否需要相关主管认领' },
        { fieldName: 'useLegalPersonSeal', title: '是否使用法人章' },
        { fieldName: 'requiresGeneralManagerApproval', title: '是否需要总经理审批' },
        { fieldName: 'remarks', title: '备注' },
      ]
      // { fieldName: 'originalContractMainDataCode', title: '原合同主数据编码' },
      //   { fieldName: 'originalContractName', title: '原合同名称' },
      //   { fieldName: 'contractAmendedTotalAmount', title: '合同变更后总金额' },
    }
    // const handleExport = () => {
    //   ElMessageBox.confirm('您确认导出查询数据吗？', '批量导出', {
    //     confirmButtonText: '确认',
    //     cancelButtonText: '取消',
    //     type: 'warning',
    //   }).then(() => {
    //     console.log('批量导出')
    //     exportContractList({ ...data.params, ids: data.ids })
    //   })
    // }
    const handleUnlock = () => {
      console.log('解锁')
      if (data.ids.length) {
        ElMessageBox.confirm('您确认解锁所选中合同吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              openContractStatus(data.ids).then((res) => {
                console.log(res)
                onSearch()
                ElMessage({
                  message: '已解锁',
                  type: 'success',
                })
              })
            }
          },
        })
      } else {
        ElMessage({
          message: '请至少选择一个合同',
          type: 'warning',
        })
      }
    }
    const handleLock = () => {
      console.log('锁定')
      if (data.ids.length) {
        ElMessageBox.confirm('您确认锁定所选中合同吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
          callback: (action) => {
            if (action == 'confirm') {
              closeContractStatus(data.ids).then((res) => {
                console.log(res)
                onSearch()
                ElMessage({
                  message: '已锁定',
                  type: 'success',
                })
              })
            }
          },
        })
      } else {
        ElMessage({
          message: '请至少选择一个合同',
          type: 'warning',
        })
      }
    }
    const handleAdd = () => {
      data.currentHandle = '新增合同'
      data.editDialog = true
    }
    const handleSave = () => {
      baseForm.value.submitForm().then((res) => {
        const loading = servicesLoading({})
        if (data.currentHandle == '新增合同') {
          insertContract(contractForm).then((res) => {
            loading.close()
            if (res.data.code == 200) {
              onSearch()
              data.editDialog = false
              ElMessage({
                message: '新增成功',
                type: 'success',
              })
            }
          }).catch(()=>{
            loading.close()
          })
        } else if (data.currentHandle == '编辑合同') {
          updateContract(contractForm).then((res) => {
            loading.close()
            if (res.data.code == 200) {
              onSearch()
              data.editDialog = false
              ElMessage({
                message: '修改成功',
                type: 'success',
              })
            }
          }).catch(()=>{
            loading.close()
          })
        }
      })
    }
    const handleClose = () => {
      data.editDialog = false
      activeName.value = '1'
    }

    return {
      data,
      activeName,
      baseForm,
      getCurrentList,
      handleCurrentChange,
      handleSizeChange,
      handleEdit,
      handleDetail,
      handleRowClick,
      handleDel,
      handleAdd,
      handleSave,
      handleClose,
      closeExport,
      handleFiled,
      handleExport,
      handleLock,
      handleUnlock,
      search,
      onSearch,
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  // padding: 0 20px 20px;
  padding: 20px;
}

.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

/deep/.demo-tabs > .el-tabs__content {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

/deep/.demo-tabs > .el-tabs__content::-webkit-scrollbar {
  display: none;
  /* Chrome Safari */
}
:deep(.el-dialog__body) {
  display: block;
  padding: 10px 20px;
}
:deep(.el-dialog__header) {
  border-bottom: 1px solid rgb(234, 230, 230);
}
</style>
